package com.treasure.web.controller.corp.admin;

import com.treasure.common.model.SessionUser;
import com.treasure.common.model.SessionUserHolder;
import com.treasure.common.reponse.Response;
import com.treasure.common.types.Corp;
import com.treasure.common.model.UploadDocumentRequest;
import com.treasure.web.command.request.KnowledgeDocumentOperateRequest;
import com.treasure.web.command.request.KnowledgeDocumentRequest;
import com.treasure.web.command.response.DocumentDownloadResponse;
import com.treasure.web.command.response.KnowledgeDocumentResponse;
import com.treasure.web.command.response.KnowledgeDocumentVectorResponse;
import com.treasure.web.command.response.KnowledgeRepositoryResponse;
import com.treasure.web.service.IKnowledgeBaseService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 知识库 （企业管理后台）
 *
 * @author sunhongmin
 * @date 2023/9/1 10:38
 * @description
 */
@RequiredArgsConstructor
@RequestMapping("/treasure/knowledge")
@Controller
public class CorpKnowledgeController {

    private final IKnowledgeBaseService knowledgeBaseService;

    /**
     * 企业知识库列表
     *
     * @return
     */
    @PostMapping("/list")
    @ResponseBody
    public Response<List<KnowledgeRepositoryResponse>> knowledgeRepositoryList() {
        SessionUser sessionUser = SessionUserHolder.getAndCheckSessionUser();
        return Response.success(knowledgeBaseService.getKnowledgeRepositoryList(new Corp(sessionUser.getCorpId())));
    }

    /**
     * 知识库文档列表
     *
     * @param knowledgeDocumentRequest 知识库参数
     * @return
     */
    @PostMapping("/documents")
    @ResponseBody
    public Response<List<KnowledgeDocumentResponse>> documentList(@RequestBody KnowledgeDocumentRequest knowledgeDocumentRequest) {
        SessionUser sessionUser = SessionUserHolder.getAndCheckSessionUser();
        return Response.success(knowledgeBaseService.getDocumentList(new Corp(sessionUser.getCorpId()), knowledgeDocumentRequest));
    }

    /**
     * 知识库文件上传
     *
     * @param file        知识库文档
     * @param knowledgeId 知识库ID
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public Response<KnowledgeDocumentResponse> uploadDocument(@RequestParam(name = "file") MultipartFile file,
                                                              @RequestParam(name = "knowledgeId") Integer knowledgeId) throws IOException {
        SessionUser sessionUser = SessionUserHolder.getAndCheckSessionUser();
        UploadDocumentRequest uploadDocumentRequest = new UploadDocumentRequest();
        uploadDocumentRequest.setCorpId(sessionUser.getCorpId());
        uploadDocumentRequest.setUserId(sessionUser.getUserId());
        uploadDocumentRequest.setUserName(sessionUser.getUserName());
        uploadDocumentRequest.setKnowledgeId(knowledgeId);
        return Response.success(knowledgeBaseService.uploadDocument(file, uploadDocumentRequest));
    }

    /**
     * 文档删除
     *
     * @param knowledgeDocumentDeleteRequest
     * @return
     */
    @PostMapping("/document/delete")
    @ResponseBody
    public Response<String> deleteDocument(@RequestBody @Validated KnowledgeDocumentOperateRequest knowledgeDocumentDeleteRequest) {
        knowledgeBaseService.deleteDocument(knowledgeDocumentDeleteRequest);
        return Response.success();
    }

    /**
     * 文档检索
     *
     * @param knowledgeDocumentDeleteRequest
     * @return
     */
    @PostMapping("/document/vectors")
    @ResponseBody
    public Response<List<KnowledgeDocumentVectorResponse>> getDocumentVector(@RequestBody @Validated KnowledgeDocumentOperateRequest knowledgeDocumentDeleteRequest) {
        return Response.success(knowledgeBaseService.getDocumentVectors(knowledgeDocumentDeleteRequest));
    }

    /**
     * 文档下载
     *
     * @param knowledgeDocumentDeleteRequest
     * @return
     * @throws IOException
     */
    @PostMapping("/document/download")
    public ResponseEntity<byte[]> downloadDocument(@RequestBody @Validated KnowledgeDocumentOperateRequest knowledgeDocumentDeleteRequest, HttpServletRequest servletRequest) throws IOException {
        DocumentDownloadResponse documentDownloadResponse = knowledgeBaseService.downloadDocument(knowledgeDocumentDeleteRequest);
        HttpHeaders headers = new HttpHeaders();
        String fileName = URLEncoder.encode(documentDownloadResponse.getFileName(), "UTF-8");
        if (servletRequest.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
            // 1.IE浏览器UTF-8
            headers.setContentDispositionFormData("attachment", fileName);
        } else {
            // 2.其他浏览器attachment;filename*=utf-8'zh_cn
            headers.add("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + fileName);//重点
        }
        HttpStatus statusCode = HttpStatus.OK;
        return new ResponseEntity<>(documentDownloadResponse.getFileBytes(), headers, statusCode);
    }

}
